<?php

namespace api\modules\v1\forms\patient;

use Yii;
use yii\base\Model;
use common\models\member\Attr;
use common\models\member\Member;
use common\models\patient\User;
use common\models\base\BodyParts;
use common\models\base\PatientDiseases;
use common\models\base\Profession;
use common\models\common\Provinces;
use common\models\clinic\Clinic;
use common\models\marketing\SourceChannel;
use common\models\marketing\Tags;
use common\models\marketing\ClinicAssess;
use common\models\marketing\EffectType;
use common\models\marketing\OutpatientType;
use common\models\marketing\RiskType;
use services\statistics\ManagementReportService;

/**
 * 患者
 *
 * Class PatientForm
 * @package api\modules\v1\forms\patient
 */
class PatientForm extends Model
{
    /**
     * 患者ID
     *
     * @var
     */
    public $id;

    /**
     * 项目ID
     *
     * @var
     */
    public $project_id;

    /**
     * 患者姓名
     *
     * @var
     */
    public $name = '';

    /**
     * 患者生日
     *
     * @var
     */
    public $birthday = '';

    /**
     * 患者年龄
     *
     * @var
     */
    public $age = 0;

    /**
     * 微信昵称
     *
     * @var
     */
    public $nickname = '';

    /**
     * 微信号
     *
     * @var
     */
    public $wx_name = '';

    /**
     * 来源渠道ID
     *
     * @var
     */
    public $source_channel_id = 0;

    /**
     * 性别
     *
     * @var
     */
    public $gender = 0;

    /**
     * 手机号
     *
     * @var
     */
    public $mobile = '';

    /**
     * 城市ID
     *
     * @var
     */
    public $city_id = 0;

    /**
     * 城市名
     *
     * @var
     */
    public $city_name = '';

    /**
     * 详细地址
     *
     * @var
     */
    public $address = '';

    /**
     * 一级病种ID
     *
     * @var
     */
    public $patient_diseases_id = 0;

    /**
     * 二级病种ID
     *
     * @var
     */
    public $patient_diseases_child_id = 0;

    /**
     * 部位
     *
     * @var
     */
    public $patient_body_parts_name;

    /**
     * 标签
     *
     * @var
     */
    public $patient_tags_name;

    /**
     * 部位IDs【多个用','分割】
     *
     * @var
     */
    public $body_parts_ids;

    /**
     * 标签IDs【多个用','分割】
     *
     * @var
     */
    public $tags_ids;

    /**
     * 归属人ID
     *
     * @var
     */
    public $belong_assistant_id = 0;

    /**
     * 归属人ID
     *
     * @var
     */
    public $belong_member_id = 0;

    /**
     * 效果类型ID
     *
     * @var
     */
    public $effect_type_id = 0;

    /**
     * 风控类型ID
     *
     * @var
     */
    public $risk_type_id = 0;

    /**
     * 诊疗类型ID
     *
     * @var
     */
    public $clinic_assess_id = 0;

    /**
     * 就诊类型ID
     *
     * @var
     */
    public $outpatient_type_id = 0;

    /**
     * 诊室ID
     *
     * @var
     */
    public $clinic_id = 0;

    /**
     * 职业
     *
     * @var
     */
    public $profession = '';

    /**
     * 下次回访时间
     *
     * @var
     */
//    public $next_callback_time = 0;

    /**
     * 客服下次回访时间
     *
     * @var
     */
    public $kf_next_callback_time = 0;

    /**
     * 医助下次回访时间
     *
     * @var
     */
    public $yz_next_callback_time = 0;

    /**
     * 下次复诊时间
     *
     * @var
     */
    public $next_revisiting_time = 0;

    /**
     * 是否为抗复发【1是、0否】
     *
     * @var
     */
    public $is_anti_relapse;

    /**
     * 抗复发年限
     *
     * @var
     */
    public $anti_relapse_year;

    /**
     * 备注
     *
     * @var
     */
    public $remark = '';

    /**
     * 批量分配患者IDs【多个用','分割】
     *
     * @var
     */
    public $ids = '';

    /**
     * 批量分配归属人IDs【多个用','分割】
     *
     * @var
     */
    public $belong_member_ids = '';

    /**
     * 检验类型【1客服、2医助、3其他】
     *
     * @var
     */
    public $check_type;

    /**
     * 患者信息
     *
     * @var
     */
    protected $patient;

    /**
     * 医助归属人信息
     *
     * @var
     */
    protected $belongAssistant;

    /**
     * 归属人信息
     *
     * @var
     */
    protected $belongMember;

    /**
     * 部位列表
     *
     * @var
     */
    protected $bodyParts;

    /**
     * 新增部位IDs
     *
     * @var
     */
    protected $addBodyPartsIds = [];

    /**
     * 删除部位IDs
     *
     * @var
     */
    protected $deleteBodyPartsIds = [];

    /**
     * 标签列表
     *
     * @var
     */
    protected $tags;

    /**
     * 新增标签IDs
     *
     * @var
     */
    protected $addTagsIds = [];

    /**
     * 删除标签IDs
     *
     * @var
     */
    protected $deleteTagsIds = [];

    /**
     * 来源渠道
     *
     * @var
     */
    protected $sourceChannel;

    /**
     * 一级病种
     *
     * @var
     */
    protected $patientDiseases;

    /**
     * 二级病种
     *
     * @var
     */
    protected $patientDiseasesChild;

    /**
     * 效果类型
     *
     * @var
     */
    protected $effectType;

    /**
     * 风控类型
     *
     * @var
     */
    protected $riskType;

    /**
     * 诊疗评估
     *
     * @var
     */
    protected $clinicAssess;

    /**
     * 就诊类型
     *
     * @var
     */
    protected $outpatientType;

    /**
     * 诊室信息
     *
     * @var
     */
    protected $clinic;

    /**
     * 城市信息
     *
     * @var
     */
    protected $cityInfo;

    /**
     * 患者列表
     *
     * @var
     */
    protected $memberList;


    public function rules()
    {
        return [
            // 参数验证
            [['project_id', 'id', 'name', 'mobile', 'belong_assistant_id', 'belong_member_id', 'clinic_id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit']],
            [['project_id', 'id', 'belong_member_id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_member_id']],
            [['project_id', 'ids', 'belong_member_ids'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_batch_member_id']],
            [['project_id', 'id', 'is_anti_relapse'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_anti']],
            [['project_id', 'id', 'anti_relapse_year'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_anti_year']],
            [['project_id', 'id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_remark']],

            [['project_id'], 'checkProjectId', 'skipOnEmpty' => false, 'on' => ['edit', 'edit_member_id', 'edit_batch_member_id', 'edit_anti', 'edit_anti_year', 'edit_remark']],
            [['id'], 'checkPatient', 'skipOnEmpty' => false, 'on' => ['edit', 'edit_member_id', 'edit_anti', 'edit_anti_year', 'edit_remark']],
            [['name'], 'checkName', 'skipOnEmpty' => false, 'on' => ['edit']],
            [['birthday'], 'checkBirthday', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['age'], 'checkAge', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['nickname'], 'checkNickname', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['wx_name'], 'checkWxName', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['source_channel_id'], 'checkSourceChannelId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['gender'], 'checkGender', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['mobile'], 'checkMobile', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['city_id'], 'checkCityId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['address'], 'checkAddress', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['patient_diseases_id'], 'checkPatientDiseasesId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['patient_diseases_child_id'], 'checkPatientDiseasesChildId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['body_parts_ids'], 'checkBodyPartsIds', 'skipOnEmpty' => false, 'on' => ['edit']],
            [['tags_ids'], 'checkTagsIds', 'skipOnEmpty' => false, 'on' => ['edit', 'patient_tags']],
            [['belong_assistant_id'], 'checkBelongAssistantId', 'skipOnEmpty' => false, 'on' => ['edit']],
            [['belong_member_id'], 'checkBelongMemberId', 'skipOnEmpty' => false, 'on' => ['edit', 'edit_member_id']],
            [['effect_type_id'], 'checkEffectTypeId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['risk_type_id'], 'checkRiskTypeId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['clinic_assess_id'], 'checkClinicAssessId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['outpatient_type_id'], 'checkOutpatientTypeId', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['clinic_id'], 'checkClinicId', 'skipOnEmpty' => false, 'on' => ['edit']],
            [['profession'], 'checkProfession', 'skipOnEmpty' => true, 'on' => ['edit']],
//            [['kf_next_callback_time'], 'checkKfNextCallbackTime', 'skipOnEmpty' => false, 'on' => ['edit']],
//            [['yz_next_callback_time'], 'checkYzNextCallbackTime', 'skipOnEmpty' => false, 'on' => ['edit']],
//            [['next_revisiting_time'], 'checkNextRevisitingTime', 'skipOnEmpty' => true, 'on' => ['edit']],
            [['remark'], 'checkRemark', 'skipOnEmpty' => true, 'on' => ['edit_remark']],

            [['ids'], 'checkBatchIds', 'skipOnEmpty' => false, 'on' => ['edit_batch_member_id']],
            [['belong_member_ids'], 'checkBelongMemberIds', 'skipOnEmpty' => false, 'on' => ['edit_batch_member_id']],
            [['is_anti_relapse'], 'checkIsAntiRelapse', 'skipOnEmpty' => false, 'on' => ['edit_anti']],
            [['anti_relapse_year'], 'checkAntiRelapseYear', 'skipOnEmpty' => false, 'on' => ['edit_anti_year']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 新增
        // $scenarios['create'] = ['project_id', 'name', 'status'];

        // 编辑
        $scenarios['edit'] = ['project_id', 'id', 'name', 'birthday', 'age', 'nickname', 'wx_name', 'source_channel_id', 'gender', 'mobile', 'city_id', 'address', 'patient_diseases_id', 'patient_diseases_child_id', 'body_parts_ids', 'tags_ids', 'belong_assistant_id', 'belong_member_id', 'effect_type_id', 'risk_type_id', 'clinic_assess_id', 'outpatient_type_id', 'clinic_id', 'profession', 'check_type'];

        // 删除
        // $scenarios['delete'] = ['project_id', 'id'];

        // 更改患者标签
        $scenarios['patient_tags'] = ['project_id', 'id', 'tags_ids'];

        // 分配患者
        $scenarios['edit_member_id'] = ['project_id', 'id', 'belong_member_id'];

        // 批量分配患者
        $scenarios['edit_batch_member_id'] = ['project_id', 'ids', 'belong_member_ids', 'check_type'];

        // 编辑患者抗复发状态
        $scenarios['edit_anti'] = ['project_id', 'id', 'is_anti_relapse'];

        // 编辑患者抗复发年限
        $scenarios['edit_anti_year'] = ['project_id', 'id', 'anti_relapse_year'];

        // 编辑患者备注
        $scenarios['edit_remark'] = ['project_id', 'id', 'remark'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'id' => '患者ID',
            'project_id' => '项目ID',
            'name' => '姓名',
            'birthday' => '生日',
            'age' => '年龄',
            'nickname' => '微信昵称',
            'wx_name' => '微信号',
            'source_channel_id' => '来源渠道',
            'gender' => '性别',
            'mobile' => '手机号',
            'city_id' => '城市',
            'address' => '详细地址',
            'patient_diseases_id' => '一级病种',
            'patient_diseases_child_id' => '二级病种',
            'body_parts_ids' => '部位',
            'tags_ids' => '标签',
            'belong_assistant_id' => '医助归属人',
            'belong_member_id' => '客服归属人',
            'effect_type_id' => '效果类型',
            'risk_type_id' => '风控类型',
            'clinic_assess_id' => '诊疗评估',
            'outpatient_type_id' => '就诊类型',
            'clinic_id' => '诊室',
            'profession' => '职业',
            // 'next_callback_time' => '下次回访时间',
            'kf_next_callback_time' => '客服下次回访时间',
            'yz_next_callback_time' => '医助下次回访时间',
            'next_revisiting_time' => '下次复诊时间',
            'is_anti_relapse' => '抗复发状态',
            'anti_relapse_year' => '抗复发年限',
            'remark' => '备注',
            'ids' => '患者',
            'belong_member_ids' => '归属人',
        ];
    }

    /**
     * 检验项目ID
     *
     * @param $attribute
     * @return bool
     */
    public function checkProjectId($attribute)
    {
        if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_YES) {
            return true;
        }

        $attr = Yii::$app->services->attr->findInfo([
            'member_id' => Yii::$app->user->identity->member_id,
            'project_id' => $this->project_id,
        ]);

        if (!$attr) {
            $this->addError($attribute, '未绑定当前项目，无法操作');
            return true;
        }
    }

    /**
     * 检验患者信息
     *
     * @param $attribute
     * @return bool
     */
    public function checkPatient($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $patient = $this->getPatient();
        if (!$patient) {
            $this->addError($attribute, '参数错误[id_error]');
            return true;
        }

        if ($patient->status == User::STATUS_DELETE) {
            $this->addError($attribute, '患者已删除，无法操作');
            return true;
        }

        if ($this->getScenario() == 'edit_member_id') {
            if ($patient->belong_member_id > 0) {
                $this->addError($attribute, '患者已分配归属人，无法操作');
                return true;
            }
        } elseif ($this->getScenario() == 'edit_anti_year') {// 修改患者年限
            if ($patient->is_anti_relapse == User::IS_ANTI_RELAPSE_NO) {
                $this->addError($attribute, '非抗复发患者，无法操作');
                return true;
            }
        } elseif ($this->getScenario() == 'edit_anti') {
            // 是否展示抗复发操作
            $outpatientTypeIds = [
                ManagementReportService::OUTPATIENT_TYPE['referral'],
                ManagementReportService::OUTPATIENT_TYPE['break']
            ];
            if(!in_array($patient->outpatient_type_id, $outpatientTypeIds)) {
                $this->addError($attribute, '患者非复诊或断诊，无法操作');
                return true;
            }
        }
    }

    /**
     * 校验患者名称
     *
     * @param $attribute
     */
    public function checkName($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->name);
        if ($len > 20) {
            $this->addError($attribute, '患者姓名过长，最多20个字');
            return true;
        }

        // 是否检验
        /*$isCheck = true;
        if ($this->getScenario() == 'edit') {
            $patient = $this->getPatient();
            // 诊室名称未变【跳过】
            if ($patient->name == $this->name) {
                $isCheck = false;
            }
        }

        if ($isCheck) {
            $clinicInfo = Yii::$app->services->patientUser->findInfo([
                'project_id' => $this->project_id,
                'name' => $this->name,
                'status' => [User::STATUS_INVALID, User::STATUS_ENABLE],
            ]);

            if ($clinicInfo) {
                $this->addError($attribute, "患者【{$this->name}】已存在");
                return true;
            }
        }*/
    }

    /**
     * 校验患者生日
     *
     * @param $attribute
     */
    public function checkBirthday($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $dateArr = explode('-', $this->birthday);
        if(count($dateArr) != 3 || !checkdate($dateArr[1], $dateArr[2], $dateArr[0])) {
            $this->addError($attribute, '生日格式错误');
            return true;
        }
    }

    /**
     * 校验患者年龄
     *
     * @param $attribute
     */
    public function checkAge($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->age < 0) {
            $this->addError($attribute, '年龄不能小于0');
            return true;
        }
    }

    /**
     * 校验微信昵称
     *
     * @param $attribute
     */
    public function checkNickname($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->nickname);
        if ($len > 30) {
            $this->addError($attribute, '微信昵称过长，最多30个字节');
            return true;
        }
    }

    /**
     * 校验微信号
     *
     * @param $attribute
     */
    public function checkWxName($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->wx_name);
        if ($len > 30) {
            $this->addError($attribute, '微信号过长，最多30个字节');
            return true;
        }
    }

    /**
     * 校验来源渠道
     *
     * @param $attribute
     */
    public function checkSourceChannelId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->source_channel_id)) {
            return true;
        }

        $sourceChannel = $this->getSourceChannel();
        if (!$sourceChannel) {
            $this->addError($attribute, '参数错误[source_channel_id_error]');
            return true;
        }

        $patient = $this->getPatient();
        if ($patient->source_channel_id != $sourceChannel->id) {
            if ($sourceChannel->status != SourceChannel::STATUS_ENABLE) {
                $this->addError($attribute, '来源渠道未启用，无法操作');
                return true;
            }
        }
    }

    /**
     * 校验性别
     *
     * @param $attribute
     */
    public function checkGender($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $genders = array_keys(User::$genders);
        if (!in_array($this->gender, $genders)) {
            $this->addError($attribute, '参数错误[gender_error]');
            return true;
        }
    }

    /**
     * 校验手机号
     *
     * @param $attribute
     */
    public function checkMobile($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (strlen($this->mobile) < 11) {
            $this->addError($attribute, '请输入11位手机号');
            return true;
        }
    }

    /**
     * 校验城市id
     *
     * @param $attribute
     */
    public function checkCityId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->city_id)) {
            return true;
        }

        $city = $this->getCity();
        /*if (!$city) {
            $this->addError($attribute, '参数错误[city_id_error]');
            return true;
        }*/

        $areaId = array_keys(Provinces::$centralCity);

        /*if (!in_array($city->id, $areaId) && ($city->level != Provinces::LEVEL_CITY || in_array($city->pid, $areaId))) {
            $this->addError($attribute, '城市有误，请选择正确城市');
            return true;
        }*/

        /*if (!in_array($city->id, $areaId) && ($city->level != Provinces::LEVEL_CITY && $city->level != Provinces::LEVEL_AREA)) {
            $this->addError($attribute, '城市有误，请选择正确城市');
            return true;
        }*/
    }

    /**
     * 校验详细地址
     *
     * @param $attribute
     */
    public function checkAddress($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (mb_strlen($this->address) > 200) {
            $this->addError($attribute, '详细地址过长，最多200个字节');
            return true;
        }
    }

    /**
     * 校验病种ID
     *
     * @param $attribute
     */
    public function checkPatientDiseasesId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->patient_diseases_id)) {
            return true;
        }

        $patientDiseases = $this->getPatientDiseases();
        if (!$patientDiseases) {
            $this->addError($attribute, '参数错误[patient_diseases_id_error]');
            return true;
        }

        $patient = $this->getPatient();
        if ($patient->patient_diseases_id != $patientDiseases->id) {
            if ($patientDiseases->status != PatientDiseases::STATUS_ENABLE) {
                $this->addError($attribute, '病种未启用，无法操作');
                return true;
            }
        }

        if ($patientDiseases->pid != 0) {
            $this->addError($attribute, '非一级病种，无法操作');
            return true;
        }
    }

    /**
     * 校验二级病种ID
     *
     * @param $attribute
     */
    public function checkPatientDiseasesChildId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->patient_diseases_child_id)) {
            return true;
        }

        if (empty($this->patient_diseases_id)) {
            $this->addError($attribute, '请先选择一级病种');
            return true;
        }

        $patientDiseasesChild = $this->getPatientDiseasesChild();
        if (!$patientDiseasesChild) {
            $this->addError($attribute, '参数错误[patient_diseases_child_id_error]');
            return true;
        }

        $patient = $this->getPatient();
        if ($patient->patient_diseases_child_id != $patientDiseasesChild->id) {
            if ($patientDiseasesChild->status != PatientDiseases::STATUS_ENABLE) {
                $this->addError($attribute, '病种未启用，无法操作');
                return true;
            }
        }

        if ($patientDiseasesChild->pid == 0) {
            $this->addError($attribute, '非二级病种，无法操作');
            return true;
        }

        if ($patientDiseasesChild->pid != $this->patient_diseases_id) {
            $this->addError($attribute, '二级病种异常');
            return true;
        }
    }

    /**
     * 校验部位IDs
     *
     * @param $attribute
     */
    public function checkBodyPartsIds($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        // 部位列表
        $bodyParts = $this->getBodyParts();
        foreach ($bodyParts as $row) {
            if(!in_array($row['status'], [BodyParts::STATUS_ENABLE, BodyParts::STATUS_INVALID])) {
                $this->addError($attribute, '参数错误[body_parts_ids_error]');
                return true;
            }
        }
        $hasBodyPartsIds = array_column($bodyParts, 'id');

        // 已绑定部位
        $patientBodyParts = Yii::$app->services->patientBodyParts->findList([
            'patient_user_id' => $this->id,
            'status' => \common\models\patient\BodyParts::STATUS_ENABLE,
        ]);
        $bodyPartsIds = array_column($patientBodyParts, 'body_parts_id');

        // 删除部位IDs
        $this->deleteBodyPartsIds = array_diff($bodyPartsIds, $hasBodyPartsIds);

        // 交集，存在部分
        $hasIds = array_intersect($bodyPartsIds, $hasBodyPartsIds);

        // 新增部位IDs
        $this->addBodyPartsIds = array_diff($hasBodyPartsIds, $hasIds);
    }

    /**
     * 校验标签IDs
     *
     * @param $attribute
     */
    public function checkTagsIds($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        // 标签列表
        $tags = $this->getTags();
        foreach ($tags as $row) {
            if(!in_array($row['status'], [Tags::STATUS_ENABLE, Tags::STATUS_INVALID])) {
                $this->addError($attribute, '参数错误[tags_ids_error]');
                return true;
            }
        }
        $hasTagsIds = array_column($tags, 'id');

        // 已绑定标签
        $patientTags = Yii::$app->services->patientTags->findList([
            'patient_user_id' => $this->id,
            'status' => \common\models\patient\Tags::STATUS_ENABLE,
        ]);
        $tagsIds = array_column($patientTags, 'tags_id');

        // 删除标签IDs
        $this->deleteTagsIds = array_diff($tagsIds, $hasTagsIds);

        // 交集，存在部分
        $hasIds = array_intersect($tagsIds, $hasTagsIds);

        // 新增标签IDs
        $this->addTagsIds = array_diff($hasTagsIds, $hasIds);
    }

    /**
     * 校验医助归属人
     *
     * @param $attribute
     */
    public function checkBelongAssistantId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->belong_assistant_id == 0) {
            return true;
        }

        $belongAssistant = $this->getBelongAssistant();
        if (!$belongAssistant) {
            $this->addError($attribute, '参数错误[belong_assistant_id_error]');
            return true;
        }

        if ($belongAssistant->status != Member::STATUS_ENABLE) {
            $this->addError($attribute, '归属人未启用，请选择其他归属人');
            return true;
        }

        $attr = Yii::$app->services->attr->findInfo([
            'member_id' => $this->belong_assistant_id,
            'project_id' => $this->project_id,
        ]);
        if (!$attr) {
            $this->addError($attribute, '归属人未绑定当前项目，无法操作');
            return true;
        }

        if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_NO) {
            $myAttr = Yii::$app->services->attr->findInfo([
                'member_id' => Yii::$app->user->identity->member_id,
                'project_id' => $this->project_id,
            ]);

            if ($myAttr->is_department_leader == Attr::IS_DEPARTMENT_LEADER_NO) {// 普通员工【自己的患者】
                if (Yii::$app->user->identity->member_id != $this->belong_assistant_id) {
                    $this->addError($attribute, '归属人错误，无法操作');
                    return true;
                }
            } elseif ($myAttr->is_department_leader == Attr::IS_DEPARTMENT_LEADER_YES) {// 部门负责人【部门下所有员工的患者】
                if ($attr->department_id != $myAttr->department_id) {
                    $this->addError($attribute, '归属人错误，无法操作');
                    return true;
                }
            }
        }
    }

    /**
     * 校验归属人
     *
     * @param $attribute
     */
    public function checkBelongMemberId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->belong_member_id == 0) {
            return true;
        }

        $belongMember = $this->getBelongMember();
        if (!$belongMember) {
            $this->addError($attribute, '参数错误[belong_member_id_error]');
            return true;
        }

        if ($belongMember->status != Member::STATUS_ENABLE) {
            $this->addError($attribute, '归属人未启用，请选择其他归属人');
            return true;
        }

        $attr = Yii::$app->services->attr->findInfo([
            'member_id' => $this->belong_member_id,
            'project_id' => $this->project_id,
        ]);
        if (!$attr) {
            $this->addError($attribute, '归属人未绑定当前项目，无法操作');
            return true;
        }

        if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_NO) {
            $myAttr = Yii::$app->services->attr->findInfo([
                'member_id' => Yii::$app->user->identity->member_id,
                'project_id' => $this->project_id,
            ]);

            if ($myAttr->is_department_leader == Attr::IS_DEPARTMENT_LEADER_NO) {// 普通员工【自己的患者】
                if (Yii::$app->user->identity->member_id != $this->belong_member_id) {
                    $this->addError($attribute, '归属人错误，无法操作');
                    return true;
                }
            } elseif ($myAttr->is_department_leader == Attr::IS_DEPARTMENT_LEADER_YES) {// 部门负责人【部门下所有员工的患者】
                if ($attr->department_id != $myAttr->department_id) {
                    $this->addError($attribute, '归属人错误，无法操作');
                    return true;
                }
            }
        }
    }

    /**
     * 校验效果类型ID
     *
     * @param $attribute
     */
    public function checkEffectTypeId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->effect_type_id)) {
            return true;
        }

        $effectType = $this->getEffectType();
        if (!$effectType) {
            $this->addError($attribute, '参数错误[effect_type_id_error]');
            return true;
        }

        $patient = $this->getPatient();
        if ($patient->effect_type_id != $effectType->id) {
            if ($effectType->status != EffectType::STATUS_ENABLE) {
                $this->addError($attribute, '效果类型未启用，无法操作');
                return true;
            }
        }
    }

    /**
     * 校验风控类型ID
     *
     * @param $attribute
     */
    public function checkRiskTypeId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->risk_type_id)) {
            return true;
        }

        $riskType = $this->getRiskType();
        if (!$riskType) {
            $this->addError($attribute, '参数错误[risk_type_id_error]');
            return true;
        }

        $patient = $this->getPatient();
        if ($patient->risk_type_id != $riskType->id) {
            if ($riskType->status != RiskType::STATUS_ENABLE) {
                $this->addError($attribute, '风控类型未启用，无法操作');
                return true;
            }
        }
    }

    /**
     * 校验诊疗评估ID
     *
     * @param $attribute
     */
    public function checkClinicAssessId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->clinic_assess_id)) {
            return true;
        }

        $clinicAssess = $this->getClinicAssess();
        if (!$clinicAssess) {
            $this->addError($attribute, '参数错误[clinic_assess_id_error]');
            return true;
        }

        if ($clinicAssess->status != ClinicAssess::STATUS_ENABLE) {
            $this->addError($attribute, '诊疗评估类型未启用，无法操作');
            return true;
        }
    }

    /**
     * 校验就诊类型ID
     *
     * @param $attribute
     */
    public function checkOutpatientTypeId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (empty($this->outpatient_type_id)) {
            return true;
        }

        $outpatientType = $this->getOutpatientType();
        if (!$outpatientType) {
            $this->addError($attribute, '参数错误[outpatient_type_id_error]');
            return true;
        }

        $patient = $this->getPatient();
        if ($patient->outpatient_type_id != $outpatientType->id) {
            if ($outpatientType->status != OutpatientType::STATUS_ENABLE) {
                $this->addError($attribute, '就诊类型未启用，无法操作');
                return true;
            }
        }
    }

    /**
     * 校验诊室
     *
     * @param $attribute
     */
    public function checkClinicId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $clinic = $this->getClinic();
        if (!$clinic) {
            $this->addError($attribute, '参数错误[clinic_id_error]');
            return true;
        }

        if ($clinic->status != Clinic::STATUS_ENABLE) {
            $this->addError($attribute, '诊室未启用，无法操作');
            return true;
        }
    }

    /**
     * 校验职业
     *
     * @param $attribute
     */
    public function checkProfession($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (mb_strlen($this->profession) > 20) {
            $this->addError($attribute, '职业名称过长，最多20个字节');
            return true;
        }
    }

    /**
     * 校验客服下次回访时间
     *
     * @param $attribute
     */
    public function checkKfNextCallbackTime($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->check_type == 2) {
            $this->kf_next_callback_time = 0;
            return true;
        }

        if (empty($this->kf_next_callback_time)) {
            $this->addError($attribute, '客服下次回访时间不能为空');
            return true;
        }

        $dateArr = explode('-', $this->kf_next_callback_time);
        if(count($dateArr) != 3 || !checkdate($dateArr[1], $dateArr[2], $dateArr[0])) {
            $this->addError($attribute, '下次回访时间格式错误');
            return true;
        }

        if (strtotime($this->kf_next_callback_time) < strtotime(date('Y-m-d', Yii::$app->params['time']))) {
            $this->addError($attribute, '下次回访时间不能早于当前时间');
            return true;
        }
    }

    /**
     * 校验医助下次回访时间
     *
     * @param $attribute
     */
    public function checkYzNextCallbackTime($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->check_type == 1) {
            $this->yz_next_callback_time = 0;
            return true;
        }
        if (empty($this->yz_next_callback_time)) {
            /*$this->addError($attribute, '医助下次回访时间不能为空');
            return true;*/
        } else {
            $dateArr = explode('-', $this->yz_next_callback_time);
            if (count($dateArr) != 3 || !checkdate($dateArr[1], $dateArr[2], $dateArr[0])) {
                $this->addError($attribute, '下次回访时间格式错误');
                return true;
            }

            if (strtotime($this->yz_next_callback_time) < strtotime(date('Y-m-d', Yii::$app->params['time']))) {
                $this->addError($attribute, '下次回访时间不能早于当前时间');
                return true;
            }
        }
    }

    /**
     * 校验下次复诊时间
     *
     * @param $attribute
     */
    public function checkNextRevisitingTime($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $dateArr = explode('-', $this->next_revisiting_time);
        if(count($dateArr) != 3 || !checkdate($dateArr[1], $dateArr[2], $dateArr[0])) {
            $this->addError($attribute, '下次复诊时间格式错误');
            return true;
        }

        if (strtotime($this->next_revisiting_time) < strtotime(date('Y-m-d', Yii::$app->params['time']))) {
            $this->addError($attribute, '下次复诊时间不能早于当前时间');
            return true;
        }
    }

    /**
     * 校验备注
     *
     * @param $attribute
     */
    public function checkRemark($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (mb_strlen($this->remark) > 500) {
            $this->addError($attribute, '备注过长，最多500个字');
            return true;
        }
    }

    /**
     * 校验批量分配患者IDs
     *
     * @param $attribute
     */
    public function checkBatchIds($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        // 患者列表
        $ids = array_unique(explode(',', $this->ids));
        $patientList = Yii::$app->services->patientUser->findList([
            'id' => $ids,
            'status' => User::STATUS_ENABLE
        ]);

        if (count($patientList) != count($ids)) {
            $this->addError($attribute, '存在未启用患者，无法操作');
            return true;
        }
    }

    /**
     * 校验批量分配患者IDs
     *
     * @param $attribute
     */
    public function checkBelongMemberIds($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        // 成员IDs
        $memberIds = array_unique(explode(',', $this->belong_member_ids));
        $attrList = Yii::$app->services->attr->findList([
            'member_id' => $memberIds,
            'project_id' => $this->project_id,
        ]);

        foreach ($attrList as $row) {
            if ($this->check_type == 2) {// 医助
                if ($row['profession_id'] != Profession::ID_MEDICAL) {// 医助
                    $this->addError($attribute, '归属人非医助，无法操作');
                    return true;
                }
            } else {// 客服
                if ($row['profession_id'] != Profession::ID_CUSTOMER) {
                    $this->addError($attribute, '归属人非客服，无法操作');
                    return true;
                }
            }
        }

        $memberNum = count($memberIds);

        if (count($attrList) != $memberNum) {
            $this->addError($attribute, '归属人不在当前项目，无法操作');
            return true;
        }

        $memberList = $this->getMemberList();
        /*$memberList = Yii::$app->services->member->findList([
            'id' => $memberIds,
            'status' => Member::STATUS_ENABLE,
        ]);*/
        if (count($memberList) != $memberNum) {
            $this->addError($attribute, '存在未启用归属人，无法操作');
            return true;
        }

        // 患者人数
        $ids = array_unique(explode(',', $this->ids));
        $patientNum = count($ids);

        if ($patientNum < $memberNum) {
            $this->addError($attribute, '归属人过多，无法平分患者');
            return true;
        }
    }

    /**
     * 校验抗复发状态
     *
     * @param $attribute
     */
    public function checkIsAntiRelapse($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (!in_array($this->is_anti_relapse, [User::IS_ANTI_RELAPSE_NO, User::IS_ANTI_RELAPSE_YES])) {
            $this->addError($attribute, '参数错误[is_anti_relapse_error]');
            return true;
        }
    }

    /**
     * 校验抗复发年限
     *
     * @param $attribute
     */
    public function checkAntiRelapseYear($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->anti_relapse_year < 0) {
            $this->addError($attribute, '年限不能小于0');
            return true;
        }
    }

    /**
     * 获取患者信息
     *
     * @return User|null
     */
    public function getPatient()
    {
        if (empty($this->patient)) {
            $this->patient = Yii::$app->services->patientUser->findById($this->id);
        }

        return $this->patient;
    }

    /**
     * 获取医助归属人信息
     *
     * @return Member|null
     */
    public function getBelongAssistant()
    {
        if (empty($this->belongAssistant)) {
            $this->belongAssistant = Yii::$app->services->member->findById((int)$this->belong_assistant_id);
        }

        return $this->belongAssistant;
    }

    /**
     * 获取归属人信息
     *
     * @return Member|null
     */
    public function getBelongMember()
    {
        if (empty($this->belongMember)) {
            $this->belongMember = Yii::$app->services->member->findById((int)$this->belong_member_id);
        }

        return $this->belongMember;
    }

    /**
     * 获取部位列表
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getBodyParts()
    {
        if (is_null($this->bodyParts)) {
            // 部位IDs
            $bodyPartsIdsArr = explode(',', $this->body_parts_ids);

            // 部位列表 (暂时取消业务部位,统一用一级部位)
            $bodyParts = Yii::$app->services->bodyParts->findList([
                'id' => $bodyPartsIdsArr,
                'type' => BodyParts::TYPE_NORMAL,
                'pid' => 0
            ]);

            $this->bodyParts = $bodyParts;
        }

        return $this->bodyParts;
    }

    /**
     * 获取标签列表
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getTags()
    {
        if (is_null($this->tags)) {
            // 标签IDs
            $tagsIdsArr = explode(',', $this->tags_ids);

            // 部位列表
            $tags = Yii::$app->services->marketingTags->findList([
                'id' => $tagsIdsArr
            ]);

            $this->tags = $tags;
        }

        return $this->tags;
    }

    /**
     * 获取患者部位
     *
     * @return string
     */
    public function getPatientBodyPartsName()
    {
        if (is_null($this->patient_body_parts_name)) {
            $bodyParts = $this->getBodyParts();
            $bodyPartsNameArr = array_column($bodyParts, 'body_parts_name');

            $this->patient_body_parts_name = implode(',', $bodyPartsNameArr);
        }

        return $this->patient_body_parts_name;
    }

    /**
     * 获取患者标签
     *
     * @return string
     */
    public function getPatientTagsName()
    {
        if (is_null($this->patient_tags_name)) {
            $tags = $this->getTags();
            $tagsNameArr = array_column($tags, 'tags_name');

            $this->patient_tags_name = implode(',', $tagsNameArr);
        }

        return $this->patient_tags_name;
    }

    /**
     * 获取新增部位IDs
     *
     * @return array
     */
    public function getAddBodyPartsIds()
    {
        return $this->addBodyPartsIds;
    }

    /**
     * 获取删除部位IDs
     *
     * @return array
     */
    public function getDeleteBodyPartsIds()
    {
        return $this->deleteBodyPartsIds;
    }

    /**
     * 获取新增标签IDs
     *
     * @return array
     */
    public function getAddTagsIds()
    {
        return $this->addTagsIds;
    }

    /**
     * 获取删除标签IDs
     *
     * @return array
     */
    public function getDeleteTagsIds()
    {
        return $this->deleteTagsIds;
    }

    /**
     * 获取来源渠道信息
     *
     * @return SourceChannel|null
     */
    public function getSourceChannel()
    {
        if (is_null($this->sourceChannel)) {
            $this->sourceChannel = Yii::$app->services->marketingSourceChannel->findById((int)$this->source_channel_id);
        }

        return $this->sourceChannel;
    }


    /**
     * 获取一级病种信息
     *
     * @return PatientDiseases|null
     */
    public function getPatientDiseases()
    {
        if (is_null($this->patientDiseases)) {
            $this->patientDiseases = Yii::$app->services->patientDiseases->findById((int)$this->patient_diseases_id);
        }

        return $this->patientDiseases;
    }

    /**
     * 获取二级病种信息
     *
     * @return PatientDiseases|null
     */
    public function getPatientDiseasesChild()
    {
        if (is_null($this->patientDiseasesChild)) {
            $this->patientDiseasesChild = Yii::$app->services->patientDiseases->findById((int)$this->patient_diseases_child_id);
        }

        return $this->patientDiseasesChild;
    }

    /**
     * 获取效果类型信息
     *
     * @return EffectType|null
     */
    public function getEffectType()
    {
        if (is_null($this->effectType)) {
            $this->effectType = Yii::$app->services->marketingEffectType->findById((int)$this->effect_type_id);
        }

        return $this->effectType;
    }

    /**
     * 获取风控类型信息
     *
     * @return RiskType|null
     */
    public function getRiskType()
    {
        if (is_null($this->riskType)) {
            $this->riskType = Yii::$app->services->marketingRiskType->findById((int)$this->risk_type_id);
        }

        return $this->riskType;
    }

    /**
     * 获取诊疗评估信息
     *
     * @return ClinicAssess|null
     */
    public function getClinicAssess()
    {
        if (is_null($this->clinicAssess)) {
            $this->clinicAssess = Yii::$app->services->marketingClinicAssess->findById((int)$this->clinic_assess_id);
        }

        return $this->clinicAssess;
    }

    /**
     * 获取就诊类型信息
     *
     * @return OutpatientType|null
     */
    public function getOutpatientType()
    {
        if (is_null($this->outpatientType)) {
            $this->outpatientType = Yii::$app->services->marketingOutpatientType->findById((int)$this->outpatient_type_id);
        }

        return $this->outpatientType;
    }

    /**
     * 获取诊室信息
     *
     * @return Clinic|null
     */
    public function getClinic()
    {
        if (is_null($this->clinic)) {
            $this->clinic = Yii::$app->services->clinic->findById((int)$this->clinic_id);
        }

        return $this->clinic;
    }

    /**
     * 获取城市信息
     *
     * @return Provinces|null
     */
    public function getCity()
    {
        if (is_null($this->cityInfo)) {
            $this->cityInfo = Yii::$app->services->provinces->findById((int)$this->city_id);
        }

        return $this->cityInfo;
    }

    /**
     * 获取患者列表【批量分配】
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getMemberList()
    {
        if (is_null($this->memberList)) {
            $memberIds = array_unique(explode(',', $this->belong_member_ids));

            $this->memberList = Yii::$app->services->member->findList([
                'id' => $memberIds,
                'status' => Member::STATUS_ENABLE,
                'indexBy' => 'id',
            ]);
        }

        return $this->memberList;
    }
}
